var express = require("express");
var router = express.Router();
const tableName = "cart";
const tableNameGoods = "goods";
const tableNameOrder = "shop_order";
const tableNameOrders = "orders";
const { Success, MError } = require("../utils/Result");
const Db = require("../utils/Db");
const { getTree } = require("../utils");
const { json } = require("express");
const { orderCode } = require("../utils");

// 引入支付模块
const AlipaySdk = require('alipay-sdk').default
const AlipayFormData = require('alipay-sdk/lib/form').default

//购物车列表
router.get("/cartlist", async (req, res) => {
  // console.log(333);res.end();
  const { uid } = req["query"];
  if (!uid) {
    res.send(MError("缺少必要条件"));
    return;
  }
  let data = await Db.select(
    req,
    `SELECT a.*,b.goodsname,b.price,b.img FROM ${tableName} a LEFT JOIN ${tableNameGoods} b ON a.goodsid = b.id WHERE a.uid = '${uid}'`
  );
  // console.log(data)

  res.send(Success(data));
});
//添加购物车
router.get("/cartadd", async (req, res) => {
  let { uid, goodsid, num } = req["query"];
  const info = await Db.select(
    req,
    `SELECT * FROM ${tableName} WHERE uid = '${uid}' AND goodsid = ${goodsid}`
  );
  // console.log(info);
  let result = "";
  if (info) {
    //更新数量
    result = await Db.update(
      req,
      tableName,
      { num: parseInt(num) + info[0].num },
      ` WHERE id = ${info[0].id}`
    );
  } else {
    result = await Db.insert(req, tableName, {
      uid,
      goodsid,
      num,
      status: 1,
    });
  }
  if (result) {
    res.send(Success([], "添加成功"));
  } else {
    res.send(MError("添加失败，请查看字段信息是否正确"));
  }
});
//修改购物车
/* router.get("/cartedit", async (req, res) => {
    let { id, type } = req['query'];
    // console.log(id,type);res.end();
    if (!id) {
        res.send(MError("缺少必要条件"));
    } else {
        const info = await Db.select(req, `SELECT * FROM ${tableName} WHERE id = ${id}`);
        let data = { num: info[0].num };
        data.num = type == 1 ? --data.num : ++data.num;
        const result = await Db.update(req, tableName, data, ` WHERE id = ${id}`);
        result === true ? res.send(Success()) : res.send(MError(result));
    }
}); */

//修改购物车
router.get("/cartedit", async (req, res) => {
  let { id, num } = req["query"];
  if (!id) {
    res.send(MError("缺少必要条件"));
  } else {
    var data = { num };
    const result = await Db.update(req, tableName, data, ` WHERE id = ${id}`);
    result === true ? res.send(Success()) : res.send(MError(result));
  }
});
//删除购物车
router.get("/cartdelete", async (req, res) => {
  let { id } = req["query"];
  if (!id) {
    res.send(MError("缺少必要条件"));
  } else {
    const result = await Db.delete(
      req,
      `DELETE FROM ${tableName} WHERE id = '${id}'`
    );
    if (result === true) {
      res.send(Success([], "删除成功"));
    } else {
      res.send(MError());
    }
  }
});

///添加订单
router.get("/orderadd", async (req, res) => {
  // params包含以下参数:uid  goodsid username userphone address countmoney countnumber addtime(可以不填数据库默认有值)
  // ids:购物车数据id字符串
  let { params, idstr } = req["query"];
  let ordernumber = orderCode();////生成主订单数据订单号
  let orderInsertData = JSON.parse(params); //处理主订单数据
  orderInsertData.ordernumber=ordernumber;


  // console.log(orderInsertData);
  // 添加主订单数据
  result = await Db.insert(req, tableNameOrder, orderInsertData);
  //   console.log(result);return;
  // 注意result返回的就是新插入数据的id 接下来添加订单详情数据
  //根据购物车数据id获取所有的购物车数据，其实订单详情就是把购物车中的数据搬移到订单详情表中
  const cartData = await Db.select(
    req,
    `SELECT * FROM ${tableName} WHERE id IN (${idstr})`
  );
  //   console.log(`SELECT * FROM ${tableName} WHERE id IN (${idstr})`);return;
  // console.log(cartData);return;
  // 处理购物车数据，将购物车id去掉添加主订单id
  cartData.forEach((item,index) => {
    delete item.id;
    delete item.status;
    item.orderid = result;
    item.subordernumber = 'sub_'+index+'_'+ordernumber;//追加子订单号
  });

  // 批量添加订单详情数据
  orderresult = await Db.insertAll(req, tableNameOrders, cartData);
  //   console.log(orderresult);return;
  // 批量删除购物车中的数据
  const deleteresult = await Db.delete(
    req,
    `DELETE FROM ${tableName} WHERE id IN (${idstr})`
  );
  //   console.log(deleteresult);
  if (deleteresult) {
    res.send(Success({ outTradeNo: ordernumber }, "提交订单成功"));
  } else {
    res.send(MError("添加失败，请查看字段信息是否正确"));
  }
});

// 查询全部订单
router.get("/orders", async (req, res) => {
  // 获取uid
  let { uid } = req["query"];
  // 组装sql  连接订单主表  订单详情表 商品表
  let sql = `SELECT id,countmoney,countnumber,goodsname,img,status
                FROM (SELECT a.id,a.countmoney,a.countnumber,a.status,b.orderid,b.goodsid FROM ${tableNameOrder} a 
                    LEFT JOIN ${tableNameOrders} b ON a.id = b.orderid  and a.uid='${uid}' ) t1 
                inner JOIN (SELECT c.orderid,c.goodsid,g.goodsname,g.price,g.img FROM ${tableNameOrders} c 
                    LEFT JOIN ${tableNameGoods} g ON c.goodsid = g.id  ) t2 
                ON t1.orderid = t2.orderid AND t1.goodsid = t2.goodsid`;
  const orderData = await Db.select(req, sql);
  // 循环处理数据结构
  let dataInfo = {};
  orderData.forEach((item, index) => {
    let { id, countmoney, countnumber } = item;
    if (!dataInfo[id]) {
      dataInfo[id] = {
        id,
        countmoney,
        countnumber,
        child: [],
      };
    }
    dataInfo[id].child.push({ goodsname: item.goodsname, img: item.img });
  });
  let list = Object.values(dataInfo); // list 转换成功的数据
  console.log(list);
  res.send(Success(list));
});


//支付订单
router.post("/alipay", async (req, res) => {
  let { outTradeNo, totalAmount, type } = req['body'];

  // 验证基本参数
  if (!outTradeNo || totalAmount < 0 || (type != 1 && type != 2)) {
    res.send(MError("缺少支付参数")); return;
  }
  // 初始化插件
  const alipaySdk = new AlipaySdk({
    appId: '2021000116695752',//此处使用的是沙箱环境
    gateway: 'https://openapi.alipaydev.com/gateway.do',
    signType: 'RSA2', // 注意这里默认是RSA2， 正常不要配置
    privateKey: 'MIIEpAIBAAKCAQEAz7wEU7CrliipSM3MQ4JsSknVXsLxdzqMoEY7XgD0gvWDgmvk23X1/XQs8I9pHflCsyIkyBhow4qTeP6VM4ONqZJHOsJShFfCfWrz/lY4YuvF1Zkg7br2Nj6Y/LUebJFJYoqS/a+XnOnlKr3wQY3pyuJI3V3iTZqUo3swV8K57iVPZomGRa8EI0OHE+ApBXCgJ7O+JAo54WbXjrhpAMHqnPvjDV/NAYAxcav2lULaUMXES1lA4ErD/qfpIlNXCNmL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AJyhRHB2+VU3aDU9udydnN4TASX24hpuV4q1O9UdY2haivf+J6RXVG6Nq/Bx399LwKBgQC2jiuscjLDLH2lEqO+DG+8CwQzbyCGM+EQtQ8OcmeLr4xLq8ukHe18iPjrQvcmNT71G+x57CxPRBOO/NVfRtdILhoslErk/7Idf2N8aU6DTJP1T0JDvbMwA7J1OO0vDr8oO+VLUqFoYzoCs4TaSqL/pWjoWTGS3055+Uyos7uOkg==',
    alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmPy8DuqRP4MGazqoukOkCOzHk7brAS3AdRIrnHibkbflGDNVY9zyKFmE4wApDOazLpa+VffH8ys+1Jep5LiHHGEIxSBUzC8ZE/G96L7A1BAK7O1+hRzgN+hdgUuzMiVqowXW0zLPpoc8vu00G9H34BkKit73S8XXifvUKVafQnoHusnEzzPAZ3U8IBYCyJhSoGnLcWjETs4mGp7PkDdnWe8b2Sa+P38WkZklvVBJUflaueRQtp+rFhvJ8/q9TKe9Aig0lU2Z5X6a5Z8yGCBSabnT0RSuHfLnm2C3rjG249Q0X4Bd86x1ChgQMhchKLVcR0RCUpb1KK90vGEyztt5+wIDAQAB'
  });
  const formData = new AlipayFormData()
  // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
  // formData.setMethod('get')
  // 配置回调接口
  formData.addField('notifyUrl', 'http://aslegou.vaiwan.com/api/notifyUrl')//异步通知地址，需要配置内网穿透(钉钉)
  formData.addField('returnUrl', 'http://localhost:8080/h5/pages/order/order')//同步通知地址
  // 设置参数
  formData.addField('bizContent', {
    outTradeNo,
    productCode: 'FAST_INSTANT_TRADE_PAY',
    totalAmount,
    subject: '商品',
    body: '商品详情',
  });

  // 根据请求type类型获取请求支付form表单 1是返回手机网站支付 2是返回pc端网站支付
  let payUrl = type == 1 ? 'alipay.trade.wap.pay' : 'alipay.trade.page.pay'
  console.log(type)
  // 请求接口
  const result = await alipaySdk.exec(
    payUrl,
    {},
    { formData: formData },
  );

  // result 为可以跳转到支付链接的 url
  console.log(result);
  res.send(Success(result));
})


// 支付宝异步通知地址
router.post('/notifyUrl',async(req,res)=>{
	console.log('触发异步请求了');

	// 获取返回支付信息
	let {out_trade_no,trade_status,trade_no} = req['body'];
	if(trade_status == 'TRADE_SUCCESS'){
		// 修改主订单数据
		let updateData = {tradeno:trade_no,status:1,paytype:1};
		return Db.update(req, tableNameOrder, updateData, `WHERE ordernumber = "${out_trade_no}"`);
		res.send('success');return;
	}else{
		res.send('fail');return
	}
})

module.exports = router;


